﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Brc_PaaS.Api.Common;
using Brc_PaaS.Bll.Exceptionless;
using Brc_PaaS.Bll.System;
using Brc_PaaS.Common.Entity;
using Brc_PaaS.Common.Model.Basic;
using Brc_PaaS.Common.Model.Exceptionless;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Brc_PaaS.Core.Redis;
using Brc_PaaS.Api.Filters;

namespace Brc_PaaS.Api.Controllers.Exceptionless
{
    /// <summary>
    /// 日志接口控制器
    /// </summary>
    [Route("api/Exceptionless/[controller]")]
    [ApiController]
    [EnableCors("any")]
    [ApiExplorerSettings(GroupName = "Exceptionless")]
    public class LogController : BaseController
    {
        private IExceptionlessLog _exceptionlessLog;
        string token;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="system"></param>
        /// <param name="exceptionlessLog"></param>
        public LogController(IConfiguration configuration, ISystem system, IExceptionlessLog exceptionlessLog) : base(configuration, system)
        {
            _exceptionlessLog = exceptionlessLog;
            using (IRedisManager redisManager = new RedisManager(RedisServerEntity))
            {
                token = redisManager.GetOrFetchString("ExceptionlessTokenFresh", x =>
                {
                    return _exceptionlessLog.Login(new EplLoginModel()
                    {
                        AppKey = configuration.GetValue<string>("Exceptionless:ApiKey"),
                        Email = configuration.GetValue<string>("Exceptionless:UserName"),
                        Password = configuration.GetValue<string>("Exceptionless:PassWords")
                    })?.Data;
                }, TimeSpan.FromHours(5))?.Token;
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<BaseResponseModel> Post(WriteLogModel model)
        {
            BaseResponseModel result = new BaseResponseModel() { IsSuccess = false, Msg = string.Empty };           
            if (SystemInfo == null)
            {
                result.Msg = "未能获取到对应业务系统信息，请联系管理员";
                return Ok(result);
            }
            Ass_Exceptionless ass_Exceptionless = null;
            using (var redisManager = new RedisManager(RedisServerEntity))
            {
                ass_Exceptionless = redisManager.GetOrFetchFromHash<Ass_Exceptionless>($"Exceptionless:{SystemInfo.Id}", id => { return _exceptionlessLog.GetExceptionlessInfo(SystemInfo.Id).Data; });
            }
            if (ass_Exceptionless == null)
            {
                result.Msg = "未能获取到对应业务系统相关的日志系统信息，请您确认是否已经申请创建日志系统，且处于启用状态";
                return Ok(result);
            }
            ElpCreateLogReqModel writeModel = new ElpCreateLogReqModel()
            {
                message = model.Message,
                level = model.Level.ToString(),
                user = new ExceptionSystemModel() { identity = SystemInfo.Id, name = !string.IsNullOrEmpty(SystemInfo.Ch_Name) ? SystemInfo.Ch_Name : SystemInfo.Name },
                tags = model.Tags,
                projectid = ass_Exceptionless.ProjectId
            };
            result = _exceptionlessLog.WriteLog(writeModel,token);
            return Ok(result);
        }
        /// <summary>
        /// 查询日志
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<ResponseModel<List<EplSearchEventResModel>>> Get(QueryEventModel model)
        {
            int total = 0;
            ResponseModel<List<EplSearchEventResModel>> result = new ResponseModel<List<EplSearchEventResModel>>() { IsSuccess = false, Msg = string.Empty, Data = new List<EplSearchEventResModel>() };
            if (SystemInfo == null)
            {
                result.Msg = "未能获取到对应业务系统信息，请联系管理员";
                return Ok(new { result, total });
            }
            Ass_Exceptionless ass_Exceptionless = null;
            using (var redisManager = new RedisManager(RedisServerEntity))
            {
                ass_Exceptionless = redisManager.GetOrFetchFromHash<Ass_Exceptionless>($"Exceptionless:{SystemInfo.Id}", id => { return _exceptionlessLog.GetExceptionlessInfo(SystemInfo.Id).Data; });
            }
            if (ass_Exceptionless == null)
            {
                result.Msg = "未能获取到对应业务系统相关的日志系统信息，请您确认是否已经申请创建日志系统，且处于启用状态";
                return Ok(new { result, total });
            }
            if (model.Page <= 0) model.Page = 1;
            if (model.Limit <= 0) model.Limit = 10;
            EplSearchEventReqModel queryEntity = new EplSearchEventReqModel()
            {
                type = model.Type.ToString(),
                tags = model.Tags,
                level = model.Level.ToString().ToLower(),
                page = model.Page,
                limit = model.Limit,
                starttime = model.StartTime,
                endtime = model.EndTime,
                projectid = ass_Exceptionless.ProjectId
            };
            result = _exceptionlessLog.QueryEvents(queryEntity, out total,token);
            return Ok(new { result, total });
        }
    }
}